package com.future.dao;

import com.future.dbutils.DatabasePool;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class BaseDAO<POModel> {
	private static Logger logger = LogManager.getLogger(BaseDAO.class);

	protected DatabasePool databasePool;
	private QueryRunner queryRunner;
	private Connection conn;

	public BaseDAO() {
		databasePool = DatabasePool.getInstance();
		queryRunner = new QueryRunner(databasePool.getDataSource(), true);
	}

	public BaseDAO(Connection conn) {
		this.conn = conn;
	}

	protected boolean update(String sql, Object... params) {
		boolean flag = false;
		try {
			int i = 0;
			if (conn != null) {
				queryRunner = new QueryRunner();
				i = queryRunner.update(conn, sql, params);
			} else {
				i = queryRunner.update(sql, params);
			}
			if (i > 0)
				flag = true;
		} catch (SQLException e) {
			logger.error(e);
		}
		return flag;
	}

	protected List<Map<String, Object>> searchAsMapList(String sql,
			Object... params) {
		List<Map<String, Object>> result = null;
		try {
			result = queryRunner.query(sql, new MapListHandler(), params);
		} catch (SQLException e) {
			logger.error(e);
		}
		return result;
	}

	protected List<POModel> searchAsBeanList(String sql, Class<POModel> c,
			Object... params) {
		List<POModel> result = null;
		try {
			result = queryRunner.query(sql, new BeanListHandler<POModel>(c),
					params);
		} catch (SQLException e) {
			logger.error(e);
		}
		return result;
	}

}
